//
//  XLScanCodeVC.m
//  campus
//
//  Created by xl on 2019/12/13.
//  Copyright © 2019 xl. All rights reserved.
//

#import "XLScanCodeVC.h"
#import "XLCustomNavigationBar.h"
#import "XLUserDefaults.h"
#import "XLWebManager.h"
#import "XLScanContentVC.h"
#import "XLAppletManager.h"


@interface XLScanCodeVC ()<XLCustomNavigationBarDelegate>

@property (nonatomic, strong) XLCustomNavigationBar *navigationBar;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic, strong) XLView *topView;
@property (nonatomic, strong) XLView *leftView;
@property (nonatomic, strong) XLView *rightView;
@property (nonatomic, strong) XLView *bottomView;
@property (nonatomic, strong) XLImageView *cornerIG;
@property (nonatomic, strong) XLImageView *lineIG;
@property (nonatomic, strong) XLButton *tourchBtn;

@end

@implementation XLScanCodeVC

- (instancetype) init {
    if (self = [super init])
    {
        self.delegate = self;
        CGRect rect = [XLScanCodeVC constructScanAnimationRect];
        int extend = CGRectGetWidth(self.view.frame) / 320 * 10;
        CGFloat offset = (CGRectGetWidth(self.view.frame) + extend * 2 - CGRectGetWidth(rect)) / 2;
        self.rectOfInterest = CGRectMake(rect.origin.x - offset,
                                                rect.origin.y - offset,
                                                CGRectGetWidth(rect) + 2 * offset,
                                                CGRectGetHeight(rect) + 2 * offset);
        self.cameraWidthPercent = 0.67;
        self.scanType = ScanType_QRCode;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

+ (CGRect)constructScanAnimationRect
{
    CGSize screenXY = [UIScreen mainScreen].bounds.size;
    NSInteger focusFrameWH = screenXY.width / 320 * 220;//as wx
    int offet = 10;
    if (screenXY.height == 568)
        offet = 19;
    
    return CGRectMake((screenXY.width - focusFrameWH) / 2,
                      (screenXY.height - 64 - focusFrameWH - 83 - 50 - offet) / 2 + 64,
                      focusFrameWH,
                      focusFrameWH);
}


#pragma mark - XLCustomNavigationBarDelegate
- (void)goBackEvents {
    RunAsyncOnMainThread([self.navigationController popViewControllerAnimated:YES];)
}

#pragma mark - TBScanViewControllerDelegate
- (void)didFind:(NSArray<TBScanResult *> *)resultArray {
    //https://www.xiaolian365.com/ad/1/4-10-X000000001
    XLLog(@"扫描结果:%@",resultArray);
    if (resultArray.count > 1) {
        NSString * contant =@"";
        for (TBScanResult *result in resultArray) {
            contant = [NSString stringWithFormat:@"%@,%@",contant,result.data];
        }
        
        [self goToContentVC:contant];
    }
    //停止扫描
    [self pauseCaptureSession];
    [self initTourchButtonState];//回复按钮状态
    BOOL isValid = NO;
    NSString *scanContent = @"";

    for (TBScanResult *result in resultArray) {
        scanContent = result.data;
        NSString *resultStep1 = [result.data stringByReplacingOccurrencesOfString:@"\n" withString:@""];//去除回车键
        NSString *resultStr = [resultStep1 stringByReplacingOccurrencesOfString:@" " withString:@""];//去除空格
//        resultStr  =  @"mpaas://platformapi/startapp?appId=20001101&token=ide_qr&scheme=mpaas://platformapi/startapp?appId=2020113000003333&nbsv=1.0.4.2&nbsource=debug&nbprefer=YES&nbsn=DEBUG&nboffline=sync&nbtoken=ide_qr&enableBugme=false&chInfo=ch_scan&channelId=86dba484-9bcc-4b9a-9c6d-41580d96bf5e&enablePolyfillWorker=true&isRemoteDebug=true&enableBugme=false&websocketUrl=wss://cn-hangzhou-mproxy.cloud.alipay.com";
        
        if ([resultStr hasPrefix:@"http://"] || [resultStr hasPrefix:@"https://"]) {
            isValid = YES;
            // H5页面
            dispatch_async(dispatch_get_main_queue(), ^{
                // 先要退出当前扫描页面
                [self.navigationController popViewControllerAnimated:YES];
                // 这里要等pop完全，不然H5页面无法加入；
                sleep(2);
                // 跳转H5页面
                [XLWebManager requestOPenWebUrl:resultStr title:@""];
            });
            return;
        } else if ([resultStr hasPrefix:@"mpaas://"]) {
            // 小程序；
            // mpaas://appid=2020113000005555&url=pages/index/index         个人档案
            // mpaas://appid=2020113000001111&url=pages/index/index         签约拍摄
            NSRange range = [resultStr rangeOfString:@"mpaas://"];
            NSString *content = [resultStr substringFromIndex:(range.location + range.length)];
            NSArray<NSString*> *tempArray = [content componentsSeparatedByString:@"&"];
            
            __block NSString *appId = @"";
            [tempArray enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj containsString:@"appid="]) {
                    NSRange appIdRange = [obj rangeOfString:@"appid="];
                    appId = [obj substringFromIndex:(appIdRange.location + appIdRange.length)];
                    *stop = YES;
                }
            }];
            BOOL isTest = false;
            for (NSString * obj in tempArray) {
                if ([obj containsString:@"appId="]){
                    isTest = true;
                }
            }
            if (isTest) {
                [self gotoTestVC:resultStr];
                return;
            }
            
            __block NSString *url = @"";
            [tempArray enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj containsString:@"url="]) {
                    NSRange urlRange = [obj rangeOfString:@"url="];
                    url = [obj substringFromIndex:(urlRange.location + urlRange.length)];
                    *stop = YES;
                }
            }];
            
            // appId和url要求非空
            if (ISEmptyString(appId) || ISEmptyString(url)) {
                continue;
            }
            
            isValid = YES;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];

//                [XLAppletManager ]
//                NSString * str = [XLUserDefaults getLastAvailableToken];
//
//                NSString *queryStr = [NSString stringWithFormat:@"token=%@", str];
//
//                NSDictionary *param = @{@"page":@"pages/index/index",@"query":queryStr};
//
//                [MPNebulaAdapterInterface startTinyAppWithId:@"2020113000001111" params:param];
////                [MPNebulaAdapterInterface startTinyAppWithId:resultStr params:@{@"token":str}];
//                [MPNebulaAdapterInterface startDebugTinyAppWithUrl:resultStr];

                // 等pop完成
                sleep(2);
                // 拉起小程序
                XLAppletManager *manager = [[XLAppletManager alloc] init];
                [manager handleJumpLogic:@(1) url:url appId:appId];

            });
            return;
        } else {
            // 啥也不做
            isValid = NO;
        }
        // 注释原来的扫描处理逻辑
//        if ([resultStr hasPrefix:@"https://www.xiaolian365.com/ad/"] ||
//            [resultStr hasPrefix:@"https://www.xiaolianhb.com/ad/"] ||
//            [resultStr hasPrefix:@"https://www.xiaoliancloud.com/ad/"]) {//属于笑联二维码
//            isValid = YES;
//            NSRange range = [resultStr rangeOfString:@"/ad/"];
//            NSString *content = [resultStr substringFromIndex:(range.location + range.length)];
//            NSArray *temArr = [content componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/-"]];
//            NSString *deviceNo = temArr.lastObject;
//            dispatch_async(dispatch_get_main_queue(), ^{
//                if (self.resultBlock) {
//                    self.resultBlock(deviceNo);
//                }
//                [self.navigationController popViewControllerAnimated:YES];
//            });
//            return;
//        } else if ([resultStr hasPrefix:@"mpaas://platformapi/startapp"]) {//小程序调试
//            isValid = YES;
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self.navigationController popViewControllerAnimated:YES];
//                [MPNebulaAdapterInterface startDebugTinyAppWithUrl:resultStr];
//            });
//            return;
//        } else if ([resultStr hasPrefix:@"https://"] || [resultStr hasPrefix:@"http://"]) {
//            isValid = YES;
//            if ([resultStr containsString:@"https://www.xiaolian365.com/ad/"] ||
//                [resultStr containsString:@"https://www.xiaolianhb.com/ad/"] ||
//                [resultStr containsString:@"https://www.xiaoliancloud.com/ad/"]) {
//                //表示里面含有我们二维码
//                NSArray *containArr = [resultStr componentsSeparatedByString:@";"];
//                for (NSString *url in containArr) {
//                    if ([url hasPrefix:@"https://www.xiaolian365.com/ad/"] ||
//                        [url hasPrefix:@"https://www.xiaolianhb.com/ad/"] ||
//                        [url hasPrefix:@"https://www.xiaoliancloud.com/ad/"]) {//属于笑联二维码
//                        NSRange range = [url rangeOfString:@"/ad/"];
//                        NSString *content = [url substringFromIndex:(range.location + range.length)];
//                        NSArray *temArr = [content componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/-"]];
//                        NSString *deviceNo = temArr.lastObject;
//                        dispatch_async(dispatch_get_main_queue(), ^{
//                            if (self.resultBlock) {
//                                self.resultBlock(deviceNo);
//                            }
//                            [self.navigationController popViewControllerAnimated:YES];
//                        });
//                        return;
//                    }
//                }
//                
//            } else {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self.navigationController popViewControllerAnimated:YES];
//                });
//            }
//            return;
//        }
    }
    // 注释原来的扫描处理逻辑
//    if (!isValid) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//
//            [XLToast showComonMessage:@"请扫描正确二维码"];
//            [self.navigationController popViewControllerAnimated:YES];
//        });
//
//    }
    if (!isValid) {
        // 无效内容，在空白页面上展示
        dispatch_async(dispatch_get_main_queue(), ^{
            // 退出扫一扫页面
            [self.navigationController popViewControllerAnimated:YES];
            // 等pop完成
            sleep(2);
            // 在空白VC中展示
            XLScanContentVC *contentVC = [[XLScanContentVC alloc] init];
            contentVC.content = scanContent;
            [self.navigationController pushViewController:contentVC animated:YES];
        });
    }
}

-(void)goToContentVC:(NSString *)content{
    dispatch_async(dispatch_get_main_queue(), ^{
        // 退出扫一扫页面
        [self.navigationController popViewControllerAnimated:YES];
        // 等pop完成
        sleep(2);
        // 在空白VC中展示
        XLScanContentVC *contentVC = [[XLScanContentVC alloc] init];
        contentVC.content = content;
        [self.navigationController pushViewController:contentVC animated:YES];
    });
}

-(void)gotoTestVC:(NSString *)url{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];

//                [XLAppletManager ]
//                NSString * str = [XLUserDefaults getLastAvailableToken];
//
//                NSString *queryStr = [NSString stringWithFormat:@"token=%@", str];
//
//                NSDictionary *param = @{@"page":@"pages/index/index",@"query":queryStr};
//
//                [MPNebulaAdapterInterface startTinyAppWithId:@"2020113000001111" params:param];
////                [MPNebulaAdapterInterface startTinyAppWithId:resultStr params:@{@"token":str}];
//                [MPNebulaAdapterInterface startDebugTinyAppWithUrl:resultStr];

        // 等pop完成
        sleep(2);
        // 拉起小程序
        
        NSString * str = [XLUserDefaults getLastAvailableToken];
      
        NSString *queryStr = [NSString stringWithFormat:@"token=%@", str];
      
        NSDictionary *param = @{@"page":@"pages/index/index",@"query":queryStr};
        
        [MPNebulaAdapterInterface startDebugTinyAppWithUrl:url params:param];
    });
}

- (void)cameraPermissionDenied
{
    RunAsyncOnMainThread([self.navigationController popViewControllerAnimated:YES];)
}

- (void)cameraDidStart
{
    NSLog(@"started!!");
    RunAsyncOnMainThread([self startRepeatSlideLine];)
}

-(void)setTorchState:(TorchState)bState
{
    NSLog(@"开启闪关灯值%f  %f",self.flashOnBrightnessThreshold ,self.flashOffBrightnessThreshold);
    NSLog(@"TorchState:%lu", (unsigned long)bState);
    if (bState == TorchState_Off) {
        self.tourchBtn.hidden = NO;
        [self.tourchBtn setTitle:@"开启闪光灯" forState:UIControlStateNormal];
    } else if (bState == TorchState_On) {
        self.tourchBtn.hidden = NO;
        [self.tourchBtn setTitle:@"关闭闪关灯" forState:UIControlStateNormal];
    } else if (bState == TorchState_Disable) {
        self.tourchBtn.hidden = YES;
    }

}

- (void)buildContainerView:(UIView *)containerView {
    CGRect rect = [XLScanCodeVC constructScanAnimationRect];
    
    [containerView addSubview:self.navigationBar];
    [containerView addSubview:self.leftView];
    [containerView addSubview:self.rightView];
    [containerView addSubview:self.topView];
    [containerView addSubview:self.bottomView];
    [containerView addSubview:self.cornerIG];
    [self.cornerIG addSubview:self.lineIG];
    [self.cornerIG addSubview:self.indicatorView];
    [self.cornerIG addSubview:self.tourchBtn];
    
    _leftView.frame = CGRectMake(0, _navigationBar.height, (containerView.width - CGRectGetWidth(rect))/2.0, containerView.height - _navigationBar.height);
    _rightView.frame = CGRectMake(CGRectGetMaxX(rect), _navigationBar.height, (containerView.width - CGRectGetWidth(rect))/2.0, containerView.height - _navigationBar.height);
    _topView.frame = CGRectMake(_leftView.width, _navigationBar.height, CGRectGetWidth(rect), CGRectGetMinY(rect) - _navigationBar.height);
    _bottomView.frame = CGRectMake(_leftView.width, CGRectGetMaxY(rect), CGRectGetWidth(rect), containerView.height - CGRectGetMaxY(rect));
    _cornerIG.frame = rect;
    _lineIG.frame = CGRectMake((CGRectGetWidth(rect) - _lineIG.width)/2.0 , 0, _lineIG.width, _lineIG.height);
    _indicatorView.frame = CGRectMake((_cornerIG.width - 20)/2.0, (_cornerIG.width - 20)/2.0, 20, 20);
    [_tourchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.cornerIG).offset(-5);
        make.centerX.equalTo(self.cornerIG);
        make.size.equalTo(CGSizeMake(80, 44));
    }];
    
}

#pragma mark - private
- (void)startRepeatSlideLine
{
    CGRect frame = self.lineIG.frame;
    [UIView animateWithDuration:2.5 delay:0.0 options:UIViewAnimationOptionRepeat animations:^{
        self.lineIG.frame = CGRectMake(frame.origin.x, self.cornerIG.frame.size.height-3, frame.size.width, frame.size.height);

    } completion:nil];
}

- (void)initTourchButtonState {
    RunAsyncOnMainThread(self.tourchBtn.hidden = YES;)
    if ([self torchMode] == TorchState_On) {
        [self onTorch];
    }
}
#pragma mark - UIButton 点击事件
- (void)clickTourch:(XLButton *)sender {
    [self onTorch];
}

#pragma mark - setter/getter
- (XLCustomNavigationBar *)navigationBar {
    if (!_navigationBar) {
        _navigationBar = [[XLCustomNavigationBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, NAVIGATIONBAR_HEIGHT)];
        [_navigationBar setCustomNavigationBarTitle:@"扫一扫"];
        _navigationBar.delegate = self;
    }
    return _navigationBar;
}

- (XLView *)topView {
    if (!_topView) {
        _topView = [XLView new];
        _topView.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.5];
    }
    return _topView;
}

- (XLView *)leftView {
    if (!_leftView) {
        _leftView = [XLView new];
        _leftView.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.5];
    }
    return _leftView;
}

- (XLView *)rightView {
    if (!_rightView) {
        _rightView = [XLView new];
        _rightView.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.5];
    }
    return _rightView;
}

- (XLView *)bottomView {
    if (!_bottomView) {
        _bottomView = [XLView new];
        _bottomView.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.5];
    }
    return _bottomView;
}

- (XLImageView *)cornerIG {
    if (!_cornerIG) {
        _cornerIG = [XLImageView new];
        _cornerIG.image = XLIMAGE(@"scanQR_cropmarks");
        _cornerIG.userInteractionEnabled = YES;
    }
    return _cornerIG;
}

- (XLImageView *)lineIG {
    if (!_lineIG) {
        UIImage *image = XLIMAGE(@"ic_line_red");
        _lineIG = [XLImageView new];
        _lineIG.image = image;
        _lineIG.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    }
    return _lineIG;
}

- (UIActivityIndicatorView *)indicatorView {
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    }
    return _indicatorView;
}

- (XLButton *)tourchBtn {
    if (!_tourchBtn) {
        _tourchBtn = [XLButton new];
        _tourchBtn.titleLabel.font = [UIFont fontOfPingFangSCRegularWithSize:16];
        [_tourchBtn setCurrentButtonHotSize:CGSizeMake(80, 44)];
        [_tourchBtn setTitle:@"开启闪光灯" forState:UIControlStateNormal];//关闭闪灯光
        _tourchBtn.hidden = YES;
        [_tourchBtn setTitleColor:[UIColor colorWithHex:0xFFFFFF alpha:0.3] forState:UIControlStateNormal];
        [_tourchBtn addTarget:self action:@selector(clickTourch:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _tourchBtn;
}

@end
